using System;
using ICSharpCode.AvalonEdit.Rendering;

namespace ICSharpCode.AvalonEdit.Editing
{
    internal sealed class SelectionColorizer : ColorizingTransformer
    {
        private readonly TextArea _textArea;

        public SelectionColorizer(TextArea textArea)
        {
            if (textArea == null)
                throw new ArgumentNullException("textArea");
            _textArea = textArea;
        }

        protected override void Colorize(ITextRunConstructionContext context)
        {
            // if SelectionForeground is null, keep the existing foreground color
            if (_textArea.SelectionForeground == null)
                return;

            var lineStartOffset = context.VisualLine.FirstDocumentLine.Offset;
            var lineEndOffset = context.VisualLine.LastDocumentLine.Offset +
                                context.VisualLine.LastDocumentLine.TotalLength;

            foreach (var segment in _textArea.Selection.Segments)
            {
                int segmentStart = segment.Offset;
                int segmentEnd = segment.Offset + segment.Length;
                if (segmentEnd <= lineStartOffset)
                    continue;
                if (segmentStart >= lineEndOffset)
                    continue;
                int startColumn = context.VisualLine.GetVisualColumn(Math.Max(0, segmentStart - lineStartOffset));
                int endColumn = context.VisualLine.GetVisualColumn(segmentEnd - lineStartOffset);
                ChangeVisualElements(
                    startColumn, endColumn,
                    element => element.TextRunProperties.SetForegroundBrush(_textArea.SelectionForeground));
            }
        }
    }
}
